#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), client(nullptr)
{
    ui->setupUi(this);
    this->setWindowTitle("Chat Tcp Client");

    client = new TCPClient(this);

    connect(ui->connect_btn, &QPushButton::clicked, this, [this] {
        if (isConnected)
        {
            ui->textEdit_system_load->append("已连接到服务器，无需重复连接");
            return;
        }
        client->connectToServer(ui->lineEdit_ip_input->text(), ui->lineEdit_port_input->text().toUShort());
    });
    connect(ui->send_btn, &QPushButton::clicked, this, [this] {
        QString text = ui->textEdit_input->toPlainText(); // 取出整段文字
        if (!text.isEmpty())
        {
            client->sendMessage(text.toUtf8()); // 你的 TCPClient 接口
            ui->textEdit_input->clear();        // 清空输入区
        }
    });

    connect(client, &TCPClient::messageReceived, this,
            [this](const QByteArray &d) { ui->textEdit_msg_load->append("收: " + d); });

    connect(client, &TCPClient::connected, this, &MainWindow::on_connected);
    connect(client, &TCPClient::disconnected, this, &MainWindow::on_disconnected);
    connect(client, &TCPClient::errorOccurred, this, &MainWindow::on_errorOccurred);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_connected()
{
    ui->textEdit_system_load->append("已连接到服务器");
    isConnected = true;
}
void MainWindow::on_disconnected()
{
    ui->textEdit_system_load->append("已断开与服务器的连接");
    isConnected = false;
}
void MainWindow::on_errorOccurred(const QString &msg)
{
    ui->textEdit_system_load->append("错误: " + msg);
    isConnected = false;
}

void MainWindow::on_disconnect_btn_clicked()
{
    if (!isConnected)
    {
        ui->textEdit_system_load->append("未连接到服务器，无需断开连接");
        return;
    }
    client->disconnectFromServer();
}

void MainWindow::on_clear_msg_btn_clicked()
{
    ui->textEdit_msg_load->clear();
    ui->textEdit_system_load->clear();
}
